<?php

namespace app\api\controller;

use app\admin\model\user\Level;
use app\api\model\Poster;
use app\api\model\user\CompanyAuth;
use app\api\model\user\Feedback;
use app\api\model\user\UserAuth;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','userlevel',
        'userlevelinfo','cardtype'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        //$user = $this->auth->getUser();
        $user_model = new \app\api\model\User();
        $user = $this->auth->getUserinfo();
        //$user = \app\api\model\User::get(34);
        $label = $user_model->getLevelLabelTextAttr($user);
        $user['level_label'] = $label;
        $level_text = $user_model->getLevelList();
        if ($user['level']>0){
            $user['level_text'] = $user['level']>0?$level_text[$user['level']]:'';
        } else {
            if ($user['person_auth']!=1&&$user['company_auth']!=1){
                $user['level_text'] = '阅览会员';
            } else{
                $user['level_text'] = '互动会员';
            }
        }

        //$data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success('', $user);

    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $username = $this->request->post('username','');

        $password = $this->request->post('password');
        $email = $this->request->post('email','');
        //$mobile = $this->request->post('mobile');
        //$code = $this->request->post('code');
        if ( !$password) {
            $this->error(__('Invalid parameters'));
        }
        /*if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }*/
        /*if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }*/
        /*$ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }*/
        $ret = $this->auth->register($username, $password, $email, $username, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        //$username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        //$bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        /*if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }*/
        if ($nickname) {
            /*$exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }*/
            $user->nickname = $nickname;
        }
        //$user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform",'wechat');
        $code = $this->request->post("code");
        $config = get_addon_config('third');

        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'));
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    //设置密码
    public function setpwd()
    {
        $newpassword = $this->request->post("newpassword");

        if (!$newpassword) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        $user = \app\common\model\User::get($this->auth->id);
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    //意见反馈
    public function feedback()
    {
        $feedback_model = new Feedback();

        $data = [
            'user_id'=>$this->auth->id,
            'content'=>input('content',''),
            'images'=>input('images',''),
        ];
        if (empty($data['content'])){
            $this->error('请输入反馈内容');
        }

        $res = $feedback_model->save($data);

        $this->success('',$res);
    }

    //修改个人/单位资料信息
    public function modifiedData()
    {
        $user_model = new \app\common\model\User();
        $params = input();
        $user_model->modifiedData($params,$this->auth->id);

        $this->success();
    }

    //单位认证
    public function companyauth()
    {
        $auth_model = new CompanyAuth();
        $company_name = input('company_name','');
        if (!$company_name)$this->error('请输入单位名称');
        $business_licence_number = input('business_licence_number','');
        if (!$business_licence_number)$this->error('请输入统一社会信用代码');
        $company_attr = input('company_attr','');
        if (!$company_attr)$this->error('请输入单位属性');
        $company_image = input('company_image','');
        if (!$company_image)$this->error('请上传单位证件照');
        $bank_open_account_image = input('bank_open_account_image','');

        $exist_id_card_num = CompanyAuth::get(['business_licence_number'=>$business_licence_number]);
        if ($exist_id_card_num)$this->error('该统一社会信用代码已提交实名');
        $info = CompanyAuth::get(['user_id'=>$this->auth->id]);
        $data = [
            'user_id' => $this->auth->id,
            'company_name' => $company_name,
            'business_licence_number' => $business_licence_number,
            'company_attr' => $company_attr,
            'company_image' => $company_image,
            'bank_open_account_image' => $bank_open_account_image,
            'status'=>0
        ];
        if ($info){
            \app\common\model\User::update(['company_auth_status'=>1],['id'=>$this->auth->id]);
            $res = $auth_model->save($data,['id'=>$info['id']]);
        } else {
            $res = $auth_model->save($data);
        }

        $this->success();
    }

    //单位认证信息
    public function companyauthinfo()
    {
        $info = CompanyAuth::get(['user_id'=>$this->auth->id]);
        $this->success('',$info);
    }


    //实名认证
    public function auth()
    {
        $auth_model = new UserAuth();
        $realname = input('realname','');
        if (!$realname)$this->error('请输入真实姓名');
        $card_type = input('card_type','');
        if (!$card_type)$this->error('请选择证件类型');
        $id_card_num = input('id_card_num','');
        if (!$id_card_num)$this->error('请填写身份证号码');
        $card_font_img = input('card_font_img','');
        if (!$card_font_img)$this->error('请上传证件正面图片');
        $card_reverse_img = input('card_reverse_img','');
        if (!$card_reverse_img)$this->error('请上传证件反面图片');
        $mobile = $this->request->post('mobile','');
        /*$captcha = $this->request->post('captcha','');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }*/
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        /*if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }*/
        $exist_id_card_num = UserAuth::get(['id_card_num'=>$id_card_num]);
        if ($exist_id_card_num)$this->error('该身份证号已提交实名');
        $info = UserAuth::get(['user_id'=>$this->auth->id]);
        $data = [
            'user_id' => $this->auth->id,
            'card_type' => $card_type,
            'realname' => $realname,
            'id_card_num' => $id_card_num,
            'card_font_img' => $card_font_img,
            'card_reverse_img' => $card_reverse_img,
            'mobile' =>$mobile,
            'status'=>0
        ];
        if ($info){
            \app\common\model\User::update(['auth_status'=>1],['id'=>$this->auth->id]);
            $res = $auth_model->save($data,['id'=>$info['id']]);
        } else {
            $res = $auth_model->save($data);
        }

        $this->success();
    }

    //认证信息
    public function authinfo()
    {
        $info = UserAuth::get(['user_id'=>$this->auth->id]);
        $this->success('',$info);
    }

    //删除个人信息
    public function del()
    {
        $user = \app\common\model\User::get($this->auth->id);
        $res = $user->delete();
        if ($res){
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    //邀请好友海报
    public function invitePoster()
    {
        $page = input('page','');

        $app_type = input('app_type','h5');

        $qrcode_param[ 'suid' ] = $this->auth->id;


        try {

            $model = new Poster();

            $res = $model->poster($page,$qrcode_param,$app_type);

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('',$res);

    }

    //会员等级
    public function userlevel()
    {
        $level_model = new Level();

        $type_list = $level_model->getTypeList();
        //dump($type_list[0]);die;
        $list = [];

        foreach ($type_list as $k=>$v){
            $list[] = [
                'title'=>$type_list[$k],
                'list'=>Level::where(['type'=>$k])->field('level_id,level_name')->order('weigh desc')->select()
            ];
        }

        $this->success('',$list);
    }

    //等级信息
    public function userlevelinfo()
    {
        $level_id = input('level_id',0);

        $info = Level::get($level_id);

        $this->success('',$info);
    }

    //用户级别(针对的用户可操作的权限)
    public function showLevel()
    {

        $user = \app\api\model\User::get($this->auth->id);
        if ($user->auth_status!=2){
            if ($user->person_auth!=1&&$user->company_auth!=1){
                $user_auth = 0;
                $user_auth_txt = '阅览级';
            } elseif ($user->person_auth==1||$user->company_auth==1){
                $user_auth = 1;
                $user_auth_txt = '互动级';
            }
        } else {
            $user_auth = 2;
            $user_auth_txt = '交易级';
        }

        $data = [
            'user_auth'=>$user_auth,
            'user_auth_txt'=>$user_auth_txt
        ];

        $this->success('',$data);

    }

    //收款码
    public function collectionCode()
    {
        $user = $this->auth->getUser();

        $wx_collection_code = input('wx_collection_code','');
        $alipay_collection_code = input('alipay_collection_code','');

        if ($wx_collection_code){
            $user->wx_collection_code = $wx_collection_code;
        }

        if ($alipay_collection_code){
            $user->alipay_collection_code = $alipay_collection_code;
        }

        $user->save();

        $this->success('');
    }

    //证件类型
    public function cardType()
    {

        $data = [
            0=>'居民身份证',1=>'护照',2=>'港澳居民来往内地通行证',3=>'台湾居民来往大陆通行证',4=>'军人身份证',5=>'武装警察身份证'
        ];
        $this->success('',$data);
    }
}
